package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UpdateCartQuantitiesServlet extends HttpServlet {

    private static final String VIEW_CART = "/jsp/cart/Cart.jsp";

    private String workingItemId;
    private Cart localCart;
    private String itemIdString;
    private CartItem cartItem;
    private int localQuatity;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        localCart = (Cart)session.getAttribute("cart");
        Account account = (Account)session.getAttribute("account");
        for(int i = 0; i < localCart.getCartItemList().size();i++){
            cartItem = localCart.getCartItemList().get(i);
            itemIdString = cartItem.getItem().getItemId();
            int quantity = Integer.parseInt(request.getParameter("quantity"));
            //localQuatity = Integer.valueOf(request.getParameter(itemIdString));
            cartItem.setQuantity(quantity);
        }
        CartService cartService = new CartService();
        cartService.updateCartByUserId(account.getUsername(),localCart);
        System.out.print(account.getUsername());
        session.setAttribute("cart", localCart);


        if(account != null){
            HttpServletRequest httpRequest= request;
            String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + strBackUrl + " update the number of items in cart";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }

     // request.getRequestDispatcher(VIEW_CART).forward(request, response);
    }
}
